<template>
  <a-upload v-model:file-list="_fileList" :list-type="listType" :max-count="limitCount" :customRequest="customRequest"
    :before-upload="beforeUpload" :accept="accept" :disabled="disabled" @reject="rejectFile" @preview="handlePreview"
    @remove="handleRemove">
    <div v-if="_fileList.length < limitCount">
      <slot />
    </div>
  </a-upload>

  <a-modal :open="preview.visible" :title="preview.title" :footer="null" @cancel="handleCancel">
    <img alt="" style="width: 100%" :src="preview.src" />
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from "vue"
import api from "@/api"
import { filter } from "lodash-es"
import { message, Upload, UploadFile } from "ant-design-vue"

const emit = defineEmits(['onSuccess', "update:modelValue", "update:fileList"])

interface Props {
  modelValue?: string,
  fileList?: UploadFile[],
  busType: number,
  limitCount?: number,
  // 文件大小，单位字节
  limitSize?: number,
  listType?: "text" | "picture" | "picture-card",
  disabled?: boolean,
  accept?: string,
}

const props = withDefaults(defineProps<Props>(), {
  limitCount: 1,
  limitSize: 0,
  listType: 'text',
  fileList: () => [],
  accept: ''
})

const _fileList = ref<UploadFile[]>([])

const preview = reactive<any>({})

// 是否已初始化
let initFileList = false

watch(() => props.modelValue, (newVal) => {
  if (newVal && !initFileList) {
    _fileList.value.push({ uid: "0001", url: newVal, name: '1' })
    initFileList = true
  }
}, { immediate: true })

watch(() => props.fileList, (newValue) => {
  // 以modelValue优先
  if (props.modelValue) {
    return
  }
  _fileList.value = newValue
}, { immediate: true })

function customRequest(event: any): void {
  const params = new FormData()
  params.append('busType', String(props.busType))
  params.append('file', event.file)
  const file = filter(_fileList.value, (item) => item.uid === event.file.uid)[0]
  api.uploadFile(params).then((resp) => {
    const data = resp.data.data
    // 更新_fileList中file对象
    file.url = data.fileUrl
    file.uid = data.uuid
    file.status = 'done'
    handleSuccess(resp)
  }).catch(() => {
    file.status = 'error'
  })
}

function beforeUpload(file: any): boolean | Promise<any> {
  return new Promise((resolve, reject) => {
    if (fileSizeCheck(file)) {
      message.error('文件不能超过' + props.limitSize / 1024 / 1024 + 'MB')
      return Upload.LIST_IGNORE
    }
    resolve(file)
  })
}

const rejectFile = (): void => {
  message.error('文件格式错误')
}

const handleSuccess = (response: any): void => {
  emit("onSuccess", response)
  const data = response?.data?.data
  // const fileUrl = data?.fileUrl
  const uuid = data?.uuid
  if (uuid) {
    // 用户上传文件了，说明fileList已经初始化
    initFileList = true
    emit("update:modelValue", uuid)
    emit("update:fileList", _fileList.value)
  }
}

const handleCancel = (): void => {
  preview.visible = false
  preview.title = ''
}
const handlePreview = (file: any): void => {
  preview.src = file.url
  preview.visible = true
  preview.title = file.name
}
const handleRemove = (file: any): boolean => {
  // 更新modelValue
  if (props.modelValue) {
    emit("update:modelValue", null)
  }
  return true
}

const fileSizeCheck = (file: any): boolean => {
  console.log(file.size, 'size');
  
  if (props.limitSize <= 0) {
    return false
  }
  return file.size > props.limitSize
}
</script>
